<?php

namespace app\api\controller;

use app\api\logic\OssLogic;
use app\api\extend\ajcaptcha\CaptchaSlide;
use app\api\logic\SmsLogic;
use app\api\model\Agreement;
use app\api\validate\SendSmsValidate;
use think\App;
use think\exception\ValidateException;
use think\Request;

class UtilController extends BaseController
{
    // 获取滑动验证码
    public function getCaptchaSlide(\app\Request $request) {
        $data = CaptchaSlide::getCaptcha();
        if(!$data) {
            return $this->setError('验证码获取失败');
        }
        return $this->setSuccess($data);
    }

    // 发送短信验证码 - 验证滑动验证码
    public function sendSmsSlide(Request $request) {
        $post = $request->post();
        try {
            $this->validate($post, SendSmsValidate::class);
        } catch (ValidateException $e) {
            return $this->setError($e->getMessage());
        }

        $token = $request->post('token');
        $pointJson = $request->post('pointJson');
        if(!$token or !$pointJson) {
            return $this->setError('参数不完整,请重试');
        }

        $res = CaptchaSlide::check($token, $pointJson);
        if(!$res) {
            return $this->setError(\Debug::getDebug());
        }

        $phone = $request->post('phone');
        $res = SmsLogic::sendCode($phone);
        if(!$res) {
            return $this->setError(\Debug::getDebug());
        }
        return $this->setSuccess();
    }

    // 图片上传
    public function uploadImg(Request $request) {
        $img = $request->file('img');
        if(!$img) {
            return $this->setError('上传失败,请重试');
        }

        $projectDirName = config('oss.project_dir_name');
        if(!$projectDirName) {
            $projectDirName = 'tv';
        }
        $pathArr = [
            $projectDirName, 'upload', 'api', date('Y'), date('m'),
        ];
        $ossPath = implode('/', $pathArr);

        $bucket = config('oss.bucket'); // bucket
        $ossPath = $ossPath . '/' . date('d') . '_' . time() . randStr() . '.' . $img->getOriginalExtension(); // oss 地址
        $localPath = $img->getRealPath(); // 文件内容

        $res = false;
        // 非正式环境,走内容上传.否则,走路径上传
        if(env('env', 'local') != config('business.env_production')) {
            $content = file_get_contents($localPath);
            $res = OssLogic::publicUploadContent($bucket, $ossPath, $content);
        } else {
            $res = OssLogic::privateUpload($bucket, $ossPath, $localPath);
        }

        if(!$res) {
            return $this->setError('上传失败');
        }
        return $this->setSuccess(['oss_path' =>$ossPath]);

    }

    // 获取各种协议
    public function getAgreement() {
        $list = Agreement::getAllCommon();

        $data = [];
        foreach($list as $item) {
            $key = $item->getIdent();
            $data[$key] = $item->getContent();
        }

        return $this->setSuccess($data);
    }
}